package com.tech.thread.juc.locks.ReentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @Author: zl
 * @Date: 2019/7/26 11:12
 */
public class TryLockDemo implements Task {
    final ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public void performTask() {
        try {
            // 在指定的超时时间：不论都否获取到锁，都会返回，获取到返回true，否则返回false.非阻塞方式获取锁
            boolean flag = reentrantLock.tryLock(100, TimeUnit.MILLISECONDS);
            if (Thread.currentThread().getName().equals("pool-1-thread-1")) {
                Thread.sleep(10000);
            }
            if (flag) {
                try {
                    System.out.println(Thread.currentThread().getName() +": Lock acquired.");
                    System.out.println("Performing task...");
                } finally {
                    System.out.println(Thread.currentThread().getName() +": Lock released.");
                    reentrantLock.unlock();
                }
            }
            System.out.println("main ------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}